package com.rc.saas.mini.controller.member;

import com.github.pagehelper.PageInfo;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.constant.SessionConstants;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.member.MemberTicket;
import com.rc.saas.mini.model.rc.RcMemberFlag;
import com.rc.saas.mini.model.rc.RcMemberGainSetting;
import com.rc.saas.mini.model.tenant.TenantTicketType;
import com.rc.saas.mini.service.market.MarketActivityService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.service.member.MemberTicketService;
import com.rc.saas.mini.service.rc.RcMemberFlagService;
import com.rc.saas.mini.service.rc.RcMemberGainSettingService;
import com.rc.saas.mini.service.ticket.TenantTicketTypeService;
import com.rc.saas.mini.vo.member.MemberTicketVo;
import com.rc.saas.mini.vo.tenant.TenantTicketTypeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author wangzhengwei
 * @create 2021/4/26
 */
@Api(tags = "16.优惠券")
@Controller
@RequestMapping("/ticket")
public class MemberTicketController extends MinipBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private MemberTicketService memberTicketService;

    @Autowired
    private MarketActivityService marketActivityService;

    @Autowired
    private RcMemberFlagService rcMemberFlagService;
    @Autowired
    private TenantTicketTypeService tenantTicketTypeService;

    @Autowired
    private RcMemberGainSettingService rcMemberGainSettingService;

    /**
     * 会员拥有的优惠券
     */
    @ResponseBody
    @RequestMapping("/listPageTicket")
    @ApiOperation(value = "会员拥有的优惠券", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "elecStationId", paramType = "query", value = "站点id，(不全即所有)", required = false), @ApiImplicitParam(name = "pageNo", paramType = "query", value = "", required = false), @ApiImplicitParam(name = "usingStatus", paramType = "query", value = "0未使用，1使用，2过期 ，默认全部", required = false), @ApiImplicitParam(name = "pageSize", paramType = "query", value = "", required = false)})
    public DataTResponse<MemberTicketVo> listPageTicket(HttpServletRequest request, Long elecStationId, @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, String usingStatus, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        logger.info("MemberTicketController.listPageTicket.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
        try {
            if (elecStationId == null || "".equals(elecStationId)) {
                PageInfo<MemberTicketVo> memberTickets = memberTicketService.listPageTicket(member, usingStatus, pageNo, pageSize);
                return DataTResponse.SUCCESS_DATA(memberTickets);
            } else {
                PageInfo<MemberTicketVo> memberTickets = memberTicketService.listPageTicketByElecStationId(member, elecStationId, usingStatus, pageNo, pageSize);
                return DataTResponse.SUCCESS_DATA(memberTickets);
            }
        } catch (Exception e) {
            logger.error("查询优惠券失败", e);
            return DataTResponse.FAIL("查询优惠券失败！");
        }
    }


    @ResponseBody
    @RequestMapping("/selectMemberCenterTicket")
    @ApiOperation(value = "会员中心-优惠券", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)

    public DataTResponse<TenantTicketTypeVo> selectMemberCenterTicket(HttpServletRequest request) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        RcMemberFlag rcMemberFlag = rcMemberFlagService.selectByPrimaryKey(loginInfo.getMemberId());
        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(rcMemberFlag.getMemberId());

        TenantTicketTypeVo tenantTicketTypeVo = new TenantTicketTypeVo();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");

        //查询生日礼遇优惠券
        if (memberInfo.getBirthday() != null) {

            Calendar instance = Calendar.getInstance();
            String currentDate = instance.get(Calendar.MONTH) + "" + instance.get(Calendar.DAY_OF_MONTH);
            instance.setTime(memberInfo.getBirthday());
            String birthday = instance.get(Calendar.MONTH) + "" + instance.get(Calendar.DAY_OF_MONTH);
            //当天生日
            if (currentDate.equals(birthday)) {
                RcMemberGainSetting rcMemberGainSetting = rcMemberGainSettingService.listBirthDayByLevelSub(rcMemberFlag.getSubLevel());
                if (rcMemberGainSetting != null) {
//                    MemberTicket memberTicket = memberTicketService.selectByTicketWithMember(memberInfo.getMemberId(), rcMemberGainSetting.getTicketTypeId());
                    int memberTicketSize= memberTicketService.listByTicketWithMember(memberInfo.getMemberId(), rcMemberGainSetting.getTicketTypeId());
                    //todo 新增可领取优惠券
                    TenantTicketType tenantTicketType = tenantTicketTypeService.selectByPrimaryKey(rcMemberGainSetting.getTicketTypeId());
                    if (tenantTicketType!=null&&tenantTicketType.getRemainTicket()>0
                            &&tenantTicketType.getTicketUnitCount()>memberTicketSize) {


                        if ("1".equals(tenantTicketType.getEffectType())) {
                            if (tenantTicketType.getEffectEndDate() != null) {
                                tenantTicketType.setRemark(simpleDateFormat.format(tenantTicketType.getEffectEndDate()) + "前可使用");
                            }
                        } else {
                            tenantTicketType.setRemark("领取后" + tenantTicketType.getEffectDay() + "天内有效");
                        }

                        tenantTicketTypeVo.setTenantTicketType(tenantTicketType);
//                        if (memberTicket == null) {
                            tenantTicketTypeVo.setCount(1);
//                        }
                        logger.info("用户:{},今天生日:{},返回生日礼遇对应优惠券:{},{}", memberInfo.getMobile(), currentDate, tenantTicketType.getTicketName(), tenantTicketType.getTicketTypeId());
                        return DataTResponse.SUCCESS_DATA(tenantTicketTypeVo);
                    }
                }
            }
        }
        //return DataTResponse.SUCCESS();
        List<TenantTicketType> list = tenantTicketTypeService.listByMemberGet(loginInfo.getMemberId());

        if (list.size() == 0) {
            return DataTResponse.SUCCESS();
        }


        tenantTicketTypeVo.setTenantTicketType(list.get(0));
        //MemberTicket memberTicket = memberTicketService.selectByTicketWithMember(loginInfo.getMemberId(), list.get(0).getTicketTypeId());
        int memberTicketSize= memberTicketService.listByTicketWithMember(memberInfo.getMemberId(), list.get(0).getTicketTypeId());
        if (tenantTicketTypeVo.getTenantTicketType() != null&&tenantTicketTypeVo.getTenantTicketType().getRemainTicket()>0
                &&tenantTicketTypeVo.getTenantTicketType().getTicketUnitCount()>memberTicketSize) {
            if ("1".equals(tenantTicketTypeVo.getTenantTicketType().getEffectType())) {
                if (tenantTicketTypeVo.getTenantTicketType().getEffectEndDate() != null) {
                    tenantTicketTypeVo.getTenantTicketType().setRemark(simpleDateFormat.format(tenantTicketTypeVo.getTenantTicketType().getEffectEndDate()) + "前可使用");
                }
            } else {
                tenantTicketTypeVo.getTenantTicketType().setRemark("领取后" + tenantTicketTypeVo.getTenantTicketType().getEffectDay() + "天内有效");
            }

            tenantTicketTypeVo.setCount(1);
        }
        return DataTResponse.SUCCESS_DATA(tenantTicketTypeVo);
    }


    @ResponseBody
    @RequestMapping("/listMemberCenterTicket")
    @ApiOperation(value = "会员中心-优惠券-列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)

    public DataTResponse<List<TenantTicketTypeVo>> listMemberCenterTicket(HttpServletRequest request) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        RcMemberFlag rcMemberFlag = rcMemberFlagService.selectByPrimaryKey(loginInfo.getMemberId());
        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(rcMemberFlag.getMemberId());

        List<TenantTicketTypeVo> tenantTicketTypeVos = new ArrayList<>();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");

        //查询生日礼遇优惠券
        if (memberInfo.getBirthday() != null) {
            TenantTicketTypeVo tenantTicketTypeVo = new TenantTicketTypeVo();
            Calendar instance = Calendar.getInstance();
            String currentDate = instance.get(Calendar.MONTH) + "" + instance.get(Calendar.DAY_OF_MONTH);
            instance.setTime(memberInfo.getBirthday());
            String birthday = instance.get(Calendar.MONTH) + "" + instance.get(Calendar.DAY_OF_MONTH);
            //当天生日
            if (currentDate.equals(birthday)) {
                RcMemberGainSetting rcMemberGainSetting = rcMemberGainSettingService.listBirthDayByLevelSub(rcMemberFlag.getSubLevel());
                if (rcMemberGainSetting != null) {
                    //MemberTicket memberTicket = memberTicketService.selectByTicketWithMember(memberInfo.getMemberId(), rcMemberGainSetting.getTicketTypeId());
                    int memberTicketSize= memberTicketService.listByTicketWithMember(memberInfo.getMemberId(), rcMemberGainSetting.getTicketTypeId());
                    TenantTicketType tenantTicketType = tenantTicketTypeService.selectByPrimaryKey(rcMemberGainSetting.getTicketTypeId());

                    if (tenantTicketType!=null&&tenantTicketType.getRemainTicket()>0
                            &&tenantTicketType.getTicketUnitCount()>memberTicketSize) {
                        //todo 新增可领取优惠券
                        if ("1".equals(tenantTicketType.getEffectType())) {
                            if (tenantTicketType.getEffectEndDate() != null) {
                                tenantTicketType.setRemark(simpleDateFormat.format(tenantTicketType.getEffectEndDate()) + "前可使用");
                            }
                        } else {
                            tenantTicketType.setRemark("领取后" + tenantTicketType.getEffectDay() + "天内有效");
                        }

                        tenantTicketTypeVo.setTenantTicketType(tenantTicketType);
                        //if (memberTicket == null) {
                            tenantTicketTypeVo.setCount(1);
                        //}
                        tenantTicketTypeVos.add(tenantTicketTypeVo);
                        logger.info("用户:{},今天生日:{},返回生日礼遇对应优惠券:{},{}", memberInfo.getMobile(), currentDate, tenantTicketType.getTicketName(), tenantTicketType.getTicketTypeId());
                        //return DataTResponse.SUCCESS_DATA(tenantTicketTypeVo);
                        //tenantTicketTypeVos.add(tenantTicketTypeVo);
                        //if (tenantTicketTypeVo.getCount() >= 1) {
                        //
                        //}
                    }
                }
            }
        }
        //return DataTResponse.SUCCESS();
        List<TenantTicketType> list = tenantTicketTypeService.listByMemberGet(loginInfo.getMemberId());

        for (TenantTicketType tenantTicketType : list) {
            TenantTicketTypeVo tenantTicketTypeVo = new TenantTicketTypeVo();
            tenantTicketTypeVo.setTenantTicketType(tenantTicketType);
            //MemberTicket memberTicket = memberTicketService.selectByTicketWithMember(loginInfo.getMemberId(), tenantTicketType.getTicketTypeId());
            int memberTicketSize= memberTicketService.listByTicketWithMember(memberInfo.getMemberId(), tenantTicketType.getTicketTypeId());
            if (tenantTicketTypeVo.getTenantTicketType() != null&&tenantTicketTypeVo.getTenantTicketType().getRemainTicket()>0
                    &&tenantTicketTypeVo.getTenantTicketType().getTicketUnitCount()>memberTicketSize) {
                if ("1".equals(tenantTicketTypeVo.getTenantTicketType().getEffectType())) {
                    if (tenantTicketTypeVo.getTenantTicketType().getEffectEndDate() != null) {
                        tenantTicketTypeVo.getTenantTicketType().setRemark(simpleDateFormat.format(tenantTicketTypeVo.getTenantTicketType().getEffectEndDate()) + "前可使用");
                    }
                } else {
                    tenantTicketTypeVo.getTenantTicketType().setRemark("领取后" + tenantTicketTypeVo.getTenantTicketType().getEffectDay() + "天内有效");
                }
                tenantTicketTypeVo.setCount(1);
                tenantTicketTypeVos.add(tenantTicketTypeVo);
            }
            //if (memberTicket == null) {
            //}
            //if (tenantTicketTypeVo.getCount() >= 1) {
            //
            //}
        }
        return DataTResponse.SUCCESS_DATA(tenantTicketTypeVos);
    }

    @ResponseBody
    @RequestMapping("/getMemberCenterTicket")
    @ApiOperation(value = "会员中心-领取优惠券", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public DataTResponse<String> getMemberCenterTicket(HttpServletRequest request, Long ticketTypeId) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }

        //        MemberTicket memberTicket = memberTicketService.selectByTicketWithMember(loginInfo.getMemberId(), ticketTypeId);
        //        if (memberTicket == null) {
        memberTicketService.addTicket(ticketTypeId, loginInfo.getMemberId());
        return DataTResponse.SUCCESS();
        //        } else {
        //            return DataTResponse.FAIL("会员已经领取过");
        //        }

    }

}
